﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Keyki.NefClass.Kernel.Data;

namespace Keyki.NefClass.Kernel.Reader
{
    public class ReaderCSV : IReader
    {
        private readonly NumberFormatInfo provider;

        public ReaderCSV()
        {
            provider = new NumberFormatInfo {NumberDecimalSeparator = ","};
        }

//ReaderCSV

        #region IReader Members

        public void Parse(string fileName, DataSet dataSet)
        {
            if (dataSet == null)
                throw new NullReferenceException("Dataset is null");

            using (var file = new StreamReader(fileName))
            {
                long length = file.BaseStream.Length;
                int pos = 0;
                String line = file.ReadLine();
                Init(line, ref dataSet);
                pos += line.Length;
                //Kernel.Worker.DoWork += delegate(object s, DoWorkEventArgs args)
                {
                    while ((line = file.ReadLine()) != null)
                    {
                        GetData(line, ref dataSet);
                        pos += line.Length;
                        //Kernel.Worker.ReportProgress((int)(pos/length * 100));
                    } //while
                }
                ;
            } //using
        }

        #endregion

//Parse()

        private void Init(string line, ref DataSet dataSet)
        {
            // split row by separator and add to output list
            var data = new List<String>(line.Split(';'));

            for (int i = 0; i < data.Count - 1; i++)
            {
                var feature = new Feature(data[i]);
                dataSet.Add(feature);
            } //for
        }

//Init

        private void GetData(string line, ref DataSet dataSet)
        {
            // split row by separator and add to output list
            var data = new List<String>(line.Split(';'));

            if (data == null)
                throw new NullReferenceException();

            String className = data[data.Count - 1];

            var values = new List<double>(data.Count - 1);

            for (int i = 0; i < data.Count - 1; i++)
            {
                double value;
                try
                {
                    value = Convert.ToDouble(data[i], provider);
                } //try
                catch (FormatException)
                {
                    provider.NumberDecimalSeparator = ".";
                    value = Convert.ToDouble(data[i], provider);
                } //catch
                values.Add(value);
            } //for

            dataSet.Add(values, className);
        }

//GetData
    }

//ReaderCSV
}

//Keyki.NefClass.Kernel.Reader